import Vue from 'vue'
import Vuex from 'vuex'

import loginApi from "@/static/js/enterpriseServer/index.js"

Vue.use(Vuex)
// #ifdef APP-PLUS
import ZIM from '@/js_sdk/zego-ZIMUniplugin-JS/lib/ZIM.js';
// #endif
const store = new Vuex.Store({

	// 全局的属性变量
	state: {
		hasLogin: false,
		userInfo: {},
		statusBar: 0,
		loading: false,
		entering: false, // 对方是否正在输入 不对
		webSocketMessage: {}, //goEasy接收到的消息体
		inviteValue: 0,
		wdNum: 0,
		zim: null,
		conversationList: [],
		serverNum: 0, //企服未读数
		filtrationIds: [], //过滤的会话id
	},
	// 放一些同步方
	// 全局的同步方法(执行方式--->$store.commit("方法名"))
	mutations: {
		sum(state, a) {
			console.log("mutations", a)
			console.log("mutations", state)
			return a;
		},
		SET_STATUS_BAR(state, data) {
			state.statusBar = data
		},
		//tf作为主动控制的参数
		switch_loading(state, tf) {
			if (tf) {
				state.loading = tf;
			} else {
				state.loading = !state.loading
			}
		},
		set_entering(state, data) {
			state.entering = data
		},
		webSocketMessage(state, data) {
			state.webSocketMessage = data
		},
		set_inviteValue(state, data) {
			state.inviteValue = data
		},
		set_wdNum(state, data) {
			state.wdNum = data
		},



		set_zim(state, data) {
			state.zim = data
		},

		set_conversationList(state, data) {
			for (let item of data) {
				if (item.lastMessage) {
					let extendedData = JSON.parse(item.lastMessage.extendedData)
					if (extendedData.quiz_id) {
						state.zim.deleteConversation(item.conversationID, 0, {
							isAlsoDeleteServerConversation: true
						})
					}
				}
			}
			state.conversationList = data.sort((obj1, obj2) => {
				return obj2.orderKey - obj1.orderKey;
			})
		},

		// 更新会话列表，接受一个数组
		updata_ConversationList(state, infoList) {
			if (state.userInfo.is_major == 1) return;
			let conversationList = state.conversationList
			let filtrationIds = state.filtrationIds;

			// 创建一个新的空数组用于存放过滤后的结果
			let filteredList = [];
			for (let i = 0; i < infoList.length; i++) {
				let item = infoList[i];
				// 检查当前项的conversationID是否在filtrationIds中
				if (!filtrationIds.includes(Number(item.conversation.conversationID))) {
					// 如果不在，则将其添加到filteredList中
					filteredList.push(item);
				}
			}
			infoList = filteredList
			if (infoList.length == 0) return;
			let num = 0
			for (let item of infoList) {
				let is = false
				if (item.lastMessage) {
					let extendedData = JSON.parse(item.lastMessage.extendedData)
					if (extendedData.quiz_id) {
						state.zim.deleteConversation(item.conversationID, 0, {
							isAlsoDeleteServerConversation: true
						})
						continue;
					}
				}

				for (let i = 0; i < conversationList.length; i++) {
					if (conversationList[i].conversationID == item.conversation.conversationID) {
						conversationList.splice(i, 1, item.conversation)
						is = true
					}
				}
				num += item.conversation.unreadMessageCount
				if (!is) conversationList.push(item.conversation)
			}
			if ((num + state.wdNum) > 0) {
				uni.setTabBarBadge({
					index: 3,
					text: (num + state.wdNum) > 99 ? '99+' : '' + (num + state.wdNum)
				})
				//更新未读数
				state.serverNum = num
			} else {
				uni.removeTabBarBadge({
					index: 3
				})
			}


			console.log('会话列表', conversationList)
			state.conversationList = conversationList.sort((obj1, obj2) => {
				return obj2.orderKey - obj1.orderKey;
			})

		},

		//删除会话
		del_ConversationList(state, data) {
			let conversationList = state.conversationList
			for (let i = 0; i < conversationList.length; i++) {
				if (conversationList[i].conversationID == data.id) {
					console.log('删除会话', conversationList[i]);
					state.zim.deleteConversation(conversationList[i].conversationID, 0, {
						isAlsoDeleteServerConversation: true
					})
					conversationList.splice(i, 1)
				}
			}
			state.conversationList = conversationList
		},

		//修改企服未读数
		SET_SERVER_NUM(state, num) {
			state.serverNum = num;
		},


		//退出时清空数据
		RESET_STATE(state) {
			// 获取 state 对象的所有属性名
			Object.keys(state).forEach(key => {
				// 如果属性值是数组，清空数组
				if (Array.isArray(state[key])) {
					state[key] = []
				} else {
					// 否则，将属性值设为 null
					state[key] = null
				}
			})
		},

		//设置过滤的会话id
		set_filtration(state, data) {
			state.filtrationIds = data
		},
	},
	// 放一些异步的方法
	// 执行actions里面的方法的方式--->this.$store.dispatch("方法名字")
	actions: {
		sum(state, aObj) {
			console.log("actions", aObj)
		},
		async LogindemoMain(state, data) {
			const res = await loginApi.LogInDemoMain({
				token: data.token,
				accesstoken: data.accessToken
			})

			context.commit('sum');
		},



		//创建zim
		createZIM(context) {
			return new Promise(async (resolve, reject) => {
				// 静态同步方法，创建 zim 实例，传入 AppID。
				// create 方法仅第一次调用时会创建 ZIM 实例，后续调用会返回 null。
				ZIM.create({
					appID: 1472263955,
					appSign: '0d8c26d495532eed3a1e56f4b2e3520e177cf176f0930e0fa3157104c43deaa0'
				});
				// 通过 getInstance 获取单实例，避免热更新导致 create 多次创建返回 null。
				let zim = ZIM.getInstance();
				ZIM.getVersion().then(res => console.log('ZIM.getVersion', res))

				context.commit('set_zim', zim)
				resolve(zim)

			})
		},
		//登录zim
		ZIMLogin(context) {
			return new Promise(async (resolve, reject) => {
				try {
					let res = {
						data: {},
					};
					if (uni.getStorageSync("zegoToken")) {
						res.data.token = uni.getStorageSync("zegoToken");
						res.code = 1;
						console.log(res, 'zegoToken');
					} else {
						res = await loginApi.getZeGoToken_chat({
							user_id: context.state.userInfo.id,
						});
					}
					if (res.code == 1) {
						context.state.zim.login({
							userID: context.state.userInfo.id + "",
							userName: context.state.userInfo.nickname,
						},
							res.data.token
						)
							.then(function () {
								console.log('zim头像准备')
								try {
									let avatar = context.state.userInfo.is_server == 1 ? context
										.state.userInfo.service_info.logo : context.state.userInfo
										.avatar
									let userName = context.state.userInfo.is_server == 1 ? context
										.state.userInfo.service_info.name : context.state.userInfo
										.nickname
									if (userName)
										context.state.zim.updateUserName(userName)
									if (avatar)
										context.state.zim.updateUserAvatarUrl(avatar).then(
											function ({
												userAvatarUrl
											}) {
												// 操作成功
												console.log('换头像操作成功', userAvatarUrl)
											})
											.catch(function (err) {
												// 操作失败
												console.log('换头像操作失败')
											});
								} catch (error) {
									console.log(error)
								}
								console.log('zim头像成功')
								console.log('zim登录成功')
								context.dispatch('queryConversationList')
								resolve('登录成功')
							})
							.catch(function (err) {
								console.log('zim登陆失败')
								setTimeout(() => {
									uni.removeStorageSync("zegoToken");
									context.dispatch('ZIMLogin')
								}, 1500);
								context.state.zim.logout()
							});
					}
				} catch (error) {
					console.log('111111111111111', error);
				}
			})

		},

		//查询会话列表
		queryConversationList(context) {
			if (context.state.userInfo.is_major == 1) return;

			if (context.state.zim)
				return new Promise(async (resolve, reject) => {
					context.state.zim
						.queryConversationList({
							// 会话锚点，传空则代表从最新开始查询
							nextConversation: null,
							count: 20
						})
						.then(function ({
							conversationList
						}) {
							try {

								let result = context.state.filtrationIds
								console.log('conversationList[0]', conversationList[0])
								let filteredList = conversationList.filter(item => !result
									.includes(Number(item.conversationID)));
								conversationList = filteredList

								let num = 0
								for (let item of conversationList) {
									num += item.unreadMessageCount
								}
								if ((num + context.state.wdNum) > 0) {
									console.log('vueX执行消息未读数queryConversationList', (num + context.state.wdNum));
									uni.setTabBarBadge({
										index: 3,
										text: (num + context.state.wdNum) > 99 ? '99+' :
											'' + (num + context.state.wdNum)
									})
								} else {
									uni.removeTabBarBadge({
										index: 3
									})
								}
								//把未读数保存到state中
								context.commit('SET_SERVER_NUM', num);
								// 查询成功，开发者需要保存和维护数组内的会话对象
								context.commit('set_conversationList', conversationList)
							} catch (error) {
								console.log(error);
							}
							resolve(conversationList)
						})
						.catch(function (err) {
							// 查询失败
							reject(err)
						});
				})
		},
	},
	getters: {

	},
	modules: {

	}
})

export default store